import axios from 'axios'
import qs from "qs";

// 创建axios实例
const Axios = axios.create({
  //baseURL: "http://localhost:42774/", // api的base_url
  baseURL: "http://focus.0791hhb.com/",
  timeout: 15000,                 // 请求超时时间
  responseType: "json",
  //withCredentials: true, // 是否允许带cookie这些
  headers: {
    "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
  }
})

// request拦截器
Axios.interceptors.request.use(config => {
  // Do something before request is sent
 
  if(config.method  === 'post'){
    config.data = qs.stringify(config.data);
  }
  // 若是有做鉴权token , 就给头部带上token
  if(localStorage.token) {
    config.headers.Authorization = localStorage.token;
  }
  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug
  Promise.reject(error)
})

//返回状态判断(添加响应拦截器)
Axios.interceptors.response.use(
  response => {
    //对响应数据做些事
    const res = response.data;
    if(res.code == null){
      return Promise.reject(res);
    }
    return res;
  },
  error => {
    console.log('err' + error)// for debug
    return Promise.reject(error)
  }
);

export default {
  install: function(Vue, Option) {
    Object.defineProperty(Vue.prototype, "$http", { value: Axios });
  }
};